<template>
  <el-dialog
    title="选择菜品明细"
    top="5vh"
    :visible.sync="dialogVisible"
    width="80%"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="dish-selector">
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="菜品分类">
            <el-input
              v-model="searchForm.category"
              placeholder="请输入菜品分类"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
          <el-form-item label="菜品名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入菜品名称"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 菜品列表 -->
      <div class="dish-list">
        <div class="dish-list-header">
          <span class="dish-count">可选择的菜品: {{ dishList.length }} 个</span>
          <span class="dish-tip">已选择的菜品按钮会变为禁用状态</span>
        </div>
        <el-table
          ref="dishTable"
          :data="dishList"
          v-loading="loading"
          max-height="400"
          stripe
          border
        >
          <el-table-column prop="category" label="菜品分类" width="120" />
          <el-table-column prop="name" label="菜品名称" min-width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="base_price" label="官方参考价格" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.base_price }}
            </template>
          </el-table-column>
          <el-table-column prop="supplier_quoted_price" label="供应商报价" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.supplier_quoted_price || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button
                :type="isDishSelected(scope.row) ? 'success' : 'primary'"
                :disabled="isDishSelected(scope.row)"
                size="mini"
                @click="selectDish(scope.row)"
              >
                {{ isDishSelected(scope.row) ? '已选择' : '选择' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 已选择的菜品 -->
      <div class="selected-dishes" v-if="selectedDishes.length > 0">
        <h4>采购单菜品 ({{ selectedDishes.length }})</h4>
        <el-table :data="selectedDishes" size="mini" border>
          <el-table-column prop="category" label="菜品分类" width="120" />
          <el-table-column prop="name" label="菜品名称" min-width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="base_price" label="官方参考价格" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.base_price }}
            </template>
          </el-table-column>
          <el-table-column prop="supplier_quoted_price" label="供应商报价" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.supplier_quoted_price || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="计划数量" width="200">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.planned_quantity"
                :min="0"
                :precision="2"
                :step="0.1"
                size="mini"
                style="width: 160px"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                @click="removeDish(scope.$index)"
                style="color: #F56C6C"
              >
                移除
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="reselectDish(scope.row)"
                style="color: #409EFF"
              >
                重新选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmSelection" :loading="saving">
        保存菜品 ({{ selectedDishes.length }})
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { http } from '@/api'

export default {
  name: 'DishSelector',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    monthlyBiddingId: {
      type: [Number, String],
      required: true
    },
    supplierId: {
      type: [Number, String],
      required: true
    },
    currentMenu: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      saving: false,
      dishList: [],
      selectedDishes: [],
      searchForm: {
        category: '',
        name: ''
      }
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.loadDishList()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
      if (!val) {
        this.resetData()
      }
    }
  },
  methods: {
    async loadDishList() {
      this.loading = true
      try {
        // 获取菜品列表（基于月度比价项目的菜品，不分页）
        const res = await http.dish.list({
          monthly_bidding_id: this.monthlyBiddingId,
          pageSize: 9999, // 设置一个很大的值来获取所有数据
          ...this.searchForm
        })

        this.dishList = res.data || []

        // 获取供应商报价信息
        await this.loadSupplierQuotes()

        // 隐藏已存在的菜品
        await this.loadMenuItems()

      } catch (error) {
        console.error('加载菜品列表失败:', error)
        this.$message.error('加载菜品列表失败')
      } finally {
        this.loading = false
      }
    },

    async loadSupplierQuotes() {
      try {
        // 获取供应商报价信息
        const quoteRes = await http.supplierQuote.list({
          monthly_bidding_id: this.monthlyBiddingId,
          supplier_id: this.supplierId
        })

        const quotes = quoteRes.data || []
        const quoteMap = {}

        quotes.forEach(quote => {
          quoteMap[quote.dish_id] = quote.quoted_price
        })

        // 将供应商报价信息合并到菜品列表中
        this.dishList = this.dishList.map(dish => ({
          ...dish,
          supplier_quoted_price: quoteMap[dish.id] || null
        }))

      } catch (error) {
        console.error('加载供应商报价失败:', error)
      }
    },
    async loadMenuItems() {
      try {
        // 获取已存在的菜单项
        const res = await http.dailyMenuItem.list({
          daily_menu_id: this.currentMenu.id
        });

        const existingMenuItems = res.data || [];
        const existingDishIds = existingMenuItems.map(item => item.dish_id);

        // 不再隐藏已存在的菜品，而是让它们显示为已选择状态
        // this.dishList = this.dishList.filter(dish =>
        //   !existingDishIds.includes(dish.id)
        // );

        // 将已存在的菜单项回显到已选择列表中
        if (existingMenuItems.length > 0) {
          this.selectedDishes = existingMenuItems.map(item => ({
            id: item.dish_id,
            category: item.dish?.category || '',
            name: item.dish?.name || '',
            unit: item.dish?.unit || '',
            base_price: item.base_price,
            supplier_quoted_price: item.supplier_quoted_price,
            planned_quantity: item.planned_quantity,
            menuItemId: item.id // 保存菜单项ID，用于后续更新
          }));
        }

        console.log('已隐藏已选择的菜品:', existingDishIds.length, '个');
        console.log('已回显菜单项:', this.selectedDishes.length, '个');

      } catch (error) {
        console.error('加载已存在菜单项失败:', error);
      }
    },

    handleSearch() {
      this.loadDishList()
    },

    handleReset() {
      this.searchForm = {
        category: '',
        name: ''
      }
      this.handleSearch()
    },

    isDishSelected(dish) {
      return this.selectedDishes.some(selected => selected.id === dish.id);
    },

    selectDish(dish) {
      // 检查菜品是否已经选择
      if (this.isDishSelected(dish)) {
        this.$message.warning('该菜品已选择');
        return;
      }

      // 将菜品添加到已选择列表
      this.selectedDishes.push({
        ...dish,
        planned_quantity: 1 // 默认计划数量为1
      });

      this.$message.success('菜品已添加到采购单');
    },

    async reselectDish(dish) {
      // 如果是已存在的菜品，需要从数据库中删除
      if (dish.menuItemId) {
        try {
          await http.dailyMenuItem.delete(dish.menuItemId);
        } catch (error) {
          console.error('删除菜品失败:', error);
          this.$message.error('删除菜品失败: ' + (error.message || '未知错误'));
          return;
        }
      }

      // 从已选择列表中移除
      const index = this.selectedDishes.findIndex(selected => selected.id === dish.id);
      if (index !== -1) {
        this.selectedDishes.splice(index, 1);
        this.$message.success('菜品已移除，可以重新选择');
      }
    },

    async removeDish(index) {
      const dish = this.selectedDishes[index];

      // 如果是已存在的菜品，需要从数据库中删除
      if (dish.menuItemId) {
        try {
          await http.dailyMenuItem.delete(dish.menuItemId);
          this.$message.success('菜品已从数据库移除');
        } catch (error) {
          console.error('删除菜品失败:', error);
          this.$message.error('删除菜品失败: ' + (error.message || '未知错误'));
          return;
        }
      }

      // 从已选择列表中移除
      this.selectedDishes.splice(index, 1);

      this.$message.success('菜品已移除');
    },



    async confirmSelection() {
      if (this.selectedDishes.length === 0) {
        this.$message.warning('请至少选择一个菜品')
        return
      }

      // 验证计划数量
      const invalidDishes = this.selectedDishes.filter(dish =>
        !dish.planned_quantity || dish.planned_quantity <= 0
      )

      // if (invalidDishes.length > 0) {
      //   this.$message.warning('请为所有菜品设置有效的计划数量')
      //   return
      // }

      this.saving = true
      try {
        // 分离新增和更新的菜品
        const newDishes = this.selectedDishes.filter(dish => !dish.menuItemId);
        const updateDishes = this.selectedDishes.filter(dish => dish.menuItemId);

        // 处理新增菜品
        if (newDishes.length > 0) {
          const newMenuItems = newDishes.map(dish => ({
            daily_menu_id: this.currentMenu.id,
            dish_id: dish.id,
            base_price: dish.base_price,
            supplier_quoted_price: dish.supplier_quoted_price || dish.base_price,
            planned_quantity: dish.planned_quantity,
            status: 1 // 待采购状态
          }));

          await http.dailyMenuItem.batchCreate(newMenuItems);
        }
        if (updateDishes.length > 0) {
          await http.dailyMenuItem.batchUpdate(updateDishes.map(item => {
            return {
              id: item.menuItemId,
              planned_quantity: item.planned_quantity,
              supplier_quoted_price: item.supplier_quoted_price || 0
            }
          }));
        }
        this.$message.success(`菜品明细保存成功，新增${newDishes.length}个，更新${updateDishes.length}个`)

        // 重新加载菜品列表和菜单项
        await this.loadDishList()

        this.$emit('success')

      } catch (error) {
        await this.loadDishList()
        console.error('保存菜品明细失败:', error)
        this.$message.error('保存菜品明细失败: ' + (error.message || '未知错误'))
      } finally {
        this.saving = false
      }
    },

    resetData() {
      this.dishList = []
      this.selectedDishes = []
      this.searchForm = {
        category: '',
        name: ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
.dish-selector {
  .search-area {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .dish-list {
    margin-bottom: 20px;

    .dish-list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;
      margin-bottom: 10px;
      border-bottom: 1px solid #EBEEF5;

      .dish-count {
        font-weight: 600;
        color: #303133;
      }

      .dish-tip {
        color: #909399;
        font-size: 12px;
      }
    }
  }

  .pagination-area {
    text-align: right;
    margin-bottom: 20px;
  }

  .selected-dishes {
    margin-top: 20px;
    padding: 15px;
    background-color: #f0f9ff;
    border-radius: 4px;

    h4 {
      margin: 0 0 15px 0;
      color: #409EFF;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
